/**
 * 自定义指令
 */
import Vue from 'vue'

let _check = function (el) {
  let maxLength = parseInt(el.maxLength);
  var orgValue = el.value;
  if (maxLength > 0) {
    orgValue = orgValue.slice(0, maxLength);
  }

  if (orgValue.length == 0 || parseInt(orgValue) == 0) {
    orgValue = 0;
  } else if (orgValue.length == 1) {
    orgValue = orgValue.replace(/[^1-9]/g, '');
  } else {
    orgValue = orgValue.replace(/\D/g, '');
  }
  orgValue = parseInt(orgValue);

  if (el.max.length > 0) {
    let max = parseInt(el.max);
    orgValue = Math.min(orgValue, max);
  }

  if (el.min.length > 0) {
    let min = parseInt(el.min);
    orgValue = Math.max(orgValue, min);
  }
  el.value = orgValue;
  el._value = orgValue;
  return orgValue;
};

/**
 * 整数输入校正整数
 * 使用，在input的type为number类型的时候，调用v-emt-integer
 */
Vue.directive('emt-integer', {
  bind: function (el) {
    $(el).keyup(function (e) {
      console.log("222222");
      _check(el);
    })
  },
  unbind: function (el) {
  },
  componentUpdated: function (el) {
  },
  update: function (el, binding) {//元素值更改的时候会触发
  },
});
/**
 * 保留小数
 */
Vue.directive('emt-float', {
  bind: function (el) {
    $(el).keyup(function (e) {
      let value = el.value;
      let oldValue = el["old-data"]||"";
      let reg = /[^\d.]/g;
      let newValue = value;
      if(reg.test(value)){//true表示错误
        newValue = oldValue;
      }else{
        if(value.split(".").length>2){
          newValue = oldValue;
        }else{
          newValue = value;
        }
      }
      el.value = newValue;
      el["old-data"] = newValue;
      e.stopPropagation();
    })
  },
  unbind: function (el) {
  },
  componentUpdated: function (el) {
  },
  update: function (el, binding) {//元素值更改的时候会触发
  },
});
